package org.prail.net.core;

import java.util.ArrayList;
import java.util.List;

import org.prail.net.Configuration;
import org.prail.net.Web;
import org.prail.utils.StringUtils;
import org.prail.wrappers.SearchResult;

import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSpan;

public class Search {

	public static SearchResult[] search(final String searchText) {
		ArrayList<SearchResult> results = new ArrayList<SearchResult>();
		searchText.replaceAll(" ", "+");
		try {
			HtmlPage result = Web.getClient().getPage(
					Configuration.host + "audio?act=search&q=" + searchText
							+ "&cut=100");
			final List<?> divResults = result
					.getByXPath("//div[@class='audio_cont']");
			divResults.remove(0); // is always empty
			for (HtmlDivision div : divResults
					.toArray(new HtmlDivision[divResults.size()])) {
				final String[] data = new String[4];
				for (final HtmlElement e : div.getChildElements()) {
					if (e.getAttribute("class").equals("audio_label")) {
						for (final HtmlElement span : e.getChildElements()) {
							if (span instanceof HtmlSpan) {
								if (span.getAttribute("class").equals("title")) {
									data[1] = StringUtils.formatXml(span.asXml());
								}
								if (span.getAttribute("class").equals("artist")) {
									data[2] = StringUtils.formatXml(span.asXml());
								}
							}
						}
					}
					if (e.getAttribute("class").equals("dur")) {
						for (final HtmlElement span : e.getChildElements()) {
							if(span instanceof HtmlSpan) {
								data[3] = span.asText();
							}
						}
					}
					if (e.hasAttribute("type")) {
						data[0] = e.getAttribute("value");
					}
				}
				results.add(new SearchResult(data[0], data[1], data[2], data[3]));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Searched for: " + searchText + " [Results : " + results.size() + "]");
		return results.toArray(new SearchResult[results.size()]);
	}
}
